#!/bin/bash

PWD=`pwd`

LOC=0

function getfiles() {
	for FILE in $1/*
	do
		if test -f $FILE; then
			RES=`echo "${FILE#*.}" | grep -E '(py|java|js|kt|html|htm)$'`
			if [ $RES ]; then
				ARR=(${ARR[*]} $FILE)
			fi
		elif test -d $FILE; then
			getfiles $FILE
		fi
	done
}

function getinvalid() {
	INVALID=0
	COMM_START=0
	while read LINE
	do
		if [[ $LINE ]]; then
			TMP=`echo "$LINE" | grep -E '.*(\*/|!>)[[:blank:]]*'`
			if [[ $TMP ]]; then
				COMM_START=0
		                INVALID=`expr $INVALID + 1`
		                continue
			fi

			if [[ $COMM_START == 1 ]]; then
				INVALID=`expr $INVALID + 1`
				continue
			fi
			
			TMP=`echo "$LINE" | grep -E '[[:blank:]]*(/\*(.)*\*/|//(.)*|#(.)*|<!--(.)*!>)[[:blank:]]*'`
			if [[ $TMP ]]; then
				INVALID=`expr $INVALID + 1`
				continue
			fi

			TMP=`echo "$LINE" | grep -E '[[:blank:]]*(/\*|<!)(.*)[[:blank:]]*'`
			if [[ $TMP ]]; then
				COMM_START=1
				INVALID=`expr $INVALID + 1`
				continue
			fi
		else
			INVALID=`expr $INVALID + 1`
		fi
	done < $1
}

getfiles $PWD

for FILE in ${ARR[@]}
do
	TOTAL=`awk '{print NR}' $FILE | tail -n1`
	getinvalid $FILE
	TOTAL=`expr $TOTAL - $INVALID`
	LOC=`expr $LOC + $TOTAL`
	echo "File: $FILE, LOC: $TOTAL"
done

echo "Total LOC: $LOC"
